package cn.ultrarisk.scadmin.manager.biz.common.factory;

import cn.ultrarisk.scadmin.manager.biz.common.entity.SchedulerJob;
import cn.ultrarisk.scadmin.manager.biz.common.service.SchedulerJobService;
import cn.ultrarisk.scadmin.manager.support.SpringContextHolder;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 * QuartzJobFactory
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/5/9
 * @since V1.0
 */
public class QuartzJobFactory implements Job {
    public static final String SCHEDULE_JOB_NAME = "scheduleJob";

    private Logger log = Logger.getLogger(QuartzJobFactory.class);

    private SchedulerJobService schedulerJobService;

    public void init() {
        if (schedulerJobService == null) {
            synchronized (this) {
                if (schedulerJobService == null) {
                    schedulerJobService = SpringContextHolder.getBean(SchedulerJobService.class);
                }
            }
        }
    }

    public void execute(JobExecutionContext context) throws JobExecutionException {
        init();

        SchedulerJob schedulerJob = (SchedulerJob) context.getMergedJobDataMap().get(SCHEDULE_JOB_NAME);
        try {
            schedulerJobService.execute(schedulerJob.getId());
        } catch (Exception e) {
            log.error("invoke bean's method failure[" + schedulerJob.getBean() + "." + schedulerJob.getMethod() + "][" + e.getMessage() + "]", e);
        }
    }
}